package org.syntaxlisp.core;

import lombok.Data;

import java.util.List;

/**
 * @author HuangYijun
 * @data 2023-01-06 10:31
 **/
@Data
public class Element {

    private String value;

    private ElementType elementType;

    private List<Element> subItems;

    public Element getSub (int index) {
        return subItems.get(index);
    }

    public int getSubSize() {
        return subItems.size();
    }

    public String toString () {
        if (elementType == ElementType.LIST) {
            StringBuilder builder = new StringBuilder("" + LispListParser.LEFT_PARENTHESIS);
            for (int i = 0; i < subItems.size(); i ++) {
                builder.append(subItems.get(i).toString());
                if (i < subItems.size() - 1) {
                    builder.append(" ");
                }
            }
            builder.append(LispListParser.RIGHT_PARENTHESIS);
            return builder.toString();
        } else if (elementType == ElementType.TOKEN) {
            return value;
        } else {
            return LispListParser.SINGLE_QUOTE + escapeString(value) + LispListParser.SINGLE_QUOTE;
        }
    }

    public static String escapeString (String value) {
        StringBuilder escapesBuilder = new StringBuilder();
        for (char ch : value.toCharArray()) {
            if (ch == LispListParser.SINGLE_QUOTE || ch == LispListParser.ESCAPE) {
                escapesBuilder.append(LispListParser.ESCAPE);
            }
            escapesBuilder.append(ch);
        }
        return escapesBuilder.toString();
    }
}
